package com.xingdata.jjxc.map.navi.activity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.amap.api.maps.MapsInitializer;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.autonavi.tbt.NaviStaticInfo;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.enty.HUDParameterEntity;
import com.xingdata.jjxc.map.navi.TTSController;
import com.xingdata.jjxc.map.navi.activity.util.Utils;
import com.xingdata.jjxc.utils.SDCardTools;

/**
 * 
 * 导航界面
 * 
 * */
public class SimpleNaviActivity extends Activity implements AMapNaviListener,
		AMapNaviViewListener {
	// 导航View
	private AMapNaviView mAmapAMapNaviView;
	// 是否为模拟导航
	private boolean mIsEmulatorNavi = true;
	// 记录有哪个页面跳转而来，处理返回键
	private int mCode = -1;
	private AMapNavi mAMapNavi;
	// private Bluetooth bluetooth;
	private List<String> aMapNaviGuides;
	private String TAG = this.getClass().getName();
	private List<NaviLatLng> latLngs = new ArrayList<NaviLatLng>();
	// 所有坐标点
	// private List<NaviLatLng> CoordList = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> naviLatLngs = new ArrayList<NaviLatLng>();
	private NaviLatLng starLatLng = null;
	// private int AllLenght = 0;
	// 记录发送点的个数
	private int inPoit = 0;
	private TTSController ttsController;

	// private ImageView roadsign, turn_mark;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simplenavi);
		Bundle bundle = getIntent().getExtras();
		processBundle(bundle);
		/*
		 * 设置离线地图存储目录，在下载离线地图或初始化地图设置; 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
		 * 则需要在离线地图下载和使用地图页面都进行路径设置
		 */
		// Demo中为了其他界面可以使用下载的离线地图，使用默认位置存储，屏蔽了自定义设置
		MapsInitializer.sdcardDir = SDCardTools
				.getFilePath(SDCardTools.OFFLINE_MAP);
		init(savedInstanceState);
	}

	private void processBundle(Bundle bundle) {
		if (bundle != null) {
			mIsEmulatorNavi = bundle.getBoolean(Utils.ISEMULATOR, true);
			mCode = bundle.getInt(Utils.ACTIVITYINDEX);
			// aMapNaviGuides = getIntent().getStringArrayListExtra(
			// "aMapNaviGuides");
			// CoordList = getIntent().getParcelableArrayListExtra("CoordList");
			starLatLng = bundle.getParcelable("mNaviStart");

			// for (String length : aMapNaviGuides) {
			// AllLenght = AllLenght + Integer.parseInt(length);
			// }
		}
	}

	/**
	 * 初始化
	 * 
	 * @param savedInstanceState
	 */
	private void init(Bundle savedInstanceState) {
		mAMapNavi = AMapNavi.getInstance(this);
		mAmapAMapNaviView = (AMapNaviView) findViewById(R.id.simplenavimap);
		// turn_mark = (ImageView) findViewById(R.id.turn_mark);
		mAmapAMapNaviView.onCreate(savedInstanceState);
		mAmapAMapNaviView.setAMapNaviViewListener(this);
		mAMapNavi.setAMapNaviListener(this);
		mAMapNavi.setDetectedMode(AMapNavi.CameraAndSpecialRoadDetectedMode);
		ttsController = TTSController.getInstance(this);
		// View view =com.autonavi.tbt.g.a(this, 2130903046, null);
		// TextView titleTextView=(TextView) view.findViewById(2131427339);
		// view.setVisibility(View.GONE);
		// System.out.println("AAAA");

		ttsController.stopSpeaking();
		if (mIsEmulatorNavi) {
			// 设置模拟速度
			AMapNavi.getInstance(this).setEmulatorNaviSpeed(220);
			// 开启模拟导航
			AMapNavi.getInstance(this).startNavi(AMapNavi.EmulatorNaviMode);

		} else {
			// 开启实时导航
			AMapNavi.getInstance(this).startNavi(AMapNavi.GPSNaviMode);
			// AMapNavi.getInstance(this).startNavi(AMapNavi.CameraDetectedMode);
		}

		setAmapNaviViewOptions();
		// 通知观察者开始导航了
		// BluetoothUpdataObserver.getCommunicationUpdata().CommunicationUpdata(Bluetooth.startMark);
		// 当坐标点数量大于49的时候从50开始发送每次发送5个坐标点
		// if (CoordList.size() > 49) {
		// inPoit = 50;
		// }
	}

	private void setAmapNaviViewOptions() {
		if (mAmapAMapNaviView == null) {
			return;
		}
		AMapNaviViewOptions viewOptions = new AMapNaviViewOptions();
		viewOptions.setSettingMenuEnabled(true);// 设置导航setting可用
		viewOptions.setNaviNight(SystemTools.isNight());// 导航界面是否显示黑夜模式。true代表显示；false代表不显示。
		viewOptions.setReCalculateRouteForYaw(true);// 偏航时是否重新计算路径(计算路径需要联网）
		viewOptions.setReCalculateRouteForTrafficJam(true);// 设置交通拥挤是否重算
		viewOptions.setTrafficInfoUpdateEnabled(true);// 设置是否更新路况
		viewOptions.setCameraInfoUpdateEnabled(true);// 设置摄像头播报
		viewOptions.setScreenAlwaysBright(true);// 设置屏幕常亮情况
//		viewOptions.setNaviViewTopic(AMapNaviViewOptions.WHITE_COLOR_TOPIC);// 设置导航界面主题样式
		viewOptions.setSettingMenuEnabled(true);// 设置菜单按钮是否在导航界面显示。
		viewOptions.setLayoutVisible(true);// 设置导航界面UI是否显示
		viewOptions.setLaneInfoShow(false);// 设置导航界面UI是否显示。
		viewOptions.setTrafficBarEnabled(false);// 设置路况光柱条是否显示
		viewOptions.setTrafficLayerEnabled(false);// 设置[实时交通图层开关按钮]是否显示（只适用于驾车导航，需要联网）。
		viewOptions.setCompassEnabled(false);// 指南针是否显示

		Field fields[] = mAmapAMapNaviView.getClass().getDeclaredFields();//
		// 获得对象所有属性
		Field field = null;
		for (int i = 0; i < fields.length; i++) {
			field = fields[i];
			field.setAccessible(true);// 修改访问权限
			// 导航图标
			if (field.getName().equals("roadsign")) {
				try {
					ImageView roadsign = (ImageView) field
							.get(mAmapAMapNaviView);
					roadsign.setVisibility(View.GONE);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else if (field.getName().equals("roadsign_layout")) {
				try {
					LinearLayout roadsign_layout = (LinearLayout) field
							.get(mAmapAMapNaviView);
					// 获取图标控件
					LinearLayout childLayout = (LinearLayout) roadsign_layout
							.getChildAt(0);
					LinearLayout ccLayout = (LinearLayout) childLayout
							.getChildAt(0);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}

		}
		mAmapAMapNaviView.setViewOptions(viewOptions);

	}

	/**
	 * 
	 * 返回键监听事件
	 * */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle("提示")
					.setMessage("是否结束本次导航")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							}).setNegativeButton("取消", null).show();

		}
		// else if(mCode==Utils.SIMPLEGPSNAVI){
		// Intent intent = new Intent(SimpleNaviActivity.this,
		// SimpleGPSNaviActivity.class);
		// intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		// startActivity(intent);
		// finish();
		// }
		// else{
		// finish();
		// }
		// }
		return super.onKeyDown(keyCode, event);
	}

	// ------------------------------生命周期方法---------------------------
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mAmapAMapNaviView.onSaveInstanceState(outState);
	}

	@Override
	public void onResume() {
		super.onResume();
		mAmapAMapNaviView.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		// mAmapAMapNaviView.onPause();
		// AMapNavi.getInstance(this).stopNavi();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mAmapAMapNaviView.onDestroy();
		TTSController.getInstance(this).stopSpeaking();
		// BluetoothUpdataObserver.getCommunicationUpdata().CommunicationUpdata(
		// Bluetooth.endMark);

	}

	// 到达目的地
	@Override
	public void onArriveDestination() {
		// BluetoothUpdataObserver.getCommunicationUpdata().CommunicationUpdata(
		// Bluetooth.endMark);
	}

	@Override
	public void onArrivedWayPoint(int arg0) {

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteSuccess() {

	}

	@Override
	public void onEndEmulatorNavi() {

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		Log.i("TAG", arg0 + "" + arg1);
	}

	/**
	 * 用户手机GPS设置是否开启的回调函数。
	 */
	@Override
	public void onGpsOpenStatus(boolean arg0) {

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation arg0) {
	}

	@SuppressWarnings("static-access")
	@Override
	public void onNaviInfoUpdate(NaviInfo naviInfo) {
		int inD = naviInfo.getDirection();
		HUDParameterEntity hudParameterEntity = new HUDParameterEntity();
		latLngs.clear();
		latLngs.add(new NaviLatLng(naviInfo.m_Latitude, naviInfo.m_Longitude));
		hudParameterEntity.setNav_amp_current_roadname(naviInfo
				.getCurrentRoadName());
		hudParameterEntity.setNav_amp_seg_next_distance(naviInfo
				.getCurStepRetainDistance() + "");
		hudParameterEntity.setNav_amp_seg_next_roadname(naviInfo
				.getNextRoadName() + "");
		hudParameterEntity.setNav_amp_distance_router_leftOver(naviInfo
				.getCurStepRetainDistance() + "");
		hudParameterEntity.setNav_amp_time_router_leftOver(naviInfo
				.getCurStepRetainTime() + "");
		hudParameterEntity
				.setNav_amp_seg_turn_flag(naviInfo.getIconType() + "");
		hudParameterEntity.setNav_amp_road_limit_speed(naviInfo.getLimitSpeed()
				+ "");
		// hudParameterEntity.setNav_amp_router_locs(calculateRoute(inPoit,
		// CoordList));
		hudParameterEntity.setNav_amp_router_locs(naviInfo
				.getCurStepRetainDistance() + "");
		Log.i(TAG, hudParameterEntity.getNav_amp_seg_next_distance());
		// if (SystemInfo.isConnect) {
		// // 每个坐标点更新启一个线程队列
		// Consumer.getInstance().add(
		// new MessageTask(BluetoothGattTools.getUartService(),
		// HUDParameterEntity.toArrayList(hudParameterEntity),
		// Hud_Panid.ZXSendHudDataBeforTypeWithStart));
		// }

		// turn_mark.setImageDrawable(roadsign.getDrawable());
		// BluetoothGattTools.getUartService().sendMessage(
		// HUDParameterEntity.toArrayList(hudParameterEntity),
		// BluetoothTools.ZXSendHudDataBeforTypeWithStart);

	}

	// private String calculateRoute(int point, List<NaviLatLng> coordList) {
	// naviLatLngs.clear();
	// if (inPoit == coordList.size()) {
	// return "null";
	// }
	// // 当坐标已经发送完毕后就不再发送了
	// if (coordList.size() - point < 5) {
	// naviLatLngs.addAll(coordList.subList(inPoit, coordList.size()));
	// inPoit = coordList.size();
	// } else {
	// naviLatLngs.addAll(coordList.subList(inPoit, inPoit + 5));
	// inPoit = point + 5;
	// }
	// return LongitudeAndLatitudeTools.getLongitudeAndLatitude(naviLatLngs,
	// starLatLng);
	//
	// }

	// /**
	// * 计算当前距离到下一个路口的距离
	// *
	// * @param naviInfo
	// * @return
	// */
	// private String CalculatedLength(NaviInfo naviInfo) {
	// // 剩下的距离
	// int PathRetainDistance = naviInfo.getPathRetainDistance();
	// naviInfo.getCurStepRetainDistance();
	// // int AllLength = 0;
	// // for (String length : aMapNaviGuides) {
	// // AllLength = AllLength + Integer.parseInt(length);
	// // }
	// // 已经行驶完的路段
	// int iLenght = 0;
	// // // 行驶节点
	// int inPosition = 0;
	// // //
	// int inNode = 0;
	// boolean isNode = false;
	// // 计算出行驶节点
	// for (int i = 0; i < aMapNaviGuides.size(); i++) {
	// iLenght = iLenght + Integer.parseInt(aMapNaviGuides.get(i));
	// if (iLenght + PathRetainDistance >= AllLenght) {
	// if (!isNode) {
	// isNode = true;
	// inPosition = i;
	// Log.i(TAG, "当前节点为" + inPosition);
	// }
	// // 最后一个节点不需要计算
	// if (i < aMapNaviGuides.size() - 1) {
	// inNode = inNode
	// + Integer.parseInt(aMapNaviGuides.get(i + 1));
	// }
	//
	// }
	// }
	//
	// // 剩余所有节点长度
	// int inLenght = 0;
	// for (int j = inPosition + 1; j < aMapNaviGuides.size(); j++) {
	// inLenght = inLenght + Integer.parseInt(aMapNaviGuides.get(j));
	// }
	//
	// // 剩下路程-剩余节点长度
	// int lenght = PathRetainDistance - inLenght;
	// //
	// // // 计算出到下一路口剩余距离 （全程剩下总路程-下一个节点后的所有路程）
	// // int lenght = PathRetainDistance
	// // - inNode;
	// Log.i(TAG, "总长度" + AllLenght + "*******************" + "剩余长度" + lenght);
	//
	// return lenght + "";
	//
	// }

	@Override
	@Deprecated
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
	}

	/**
	 * 驾车导航时，如果前方遇到拥堵时需要重新计算路径的回调。
	 */
	@Override
	public void onReCalculateRouteForTrafficJam() {
		ttsController.playText("已检测到前方路段拥堵可以避开行驶");
	}

	/**
	 * 步行或驾车导航时,出现偏航后需要重新计算路径的回调函数。
	 */
	@Override
	public void onReCalculateRouteForYaw() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartNavi(int arg0) {

	}

	/**
	 * 当前方路况光柱信息有更新时回调函数。
	 */
	@Override
	public void onTrafficStatusUpdate() {

	}

	@Override
	public void onLockMap(boolean arg0) {

	}

	@Override
	public void onNaviCancel() {
		finish();
	}

	@Override
	public void onNaviMapMode(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviSetting() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviTurnClick() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNextRoadClick() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScanViewButtonClick() {
	}

	@Override
	public boolean onNaviBackClick() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void OnUpdateTrafficFacility(TrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideCross() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideLaneInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showCross(AMapNaviCross arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLaneInfo(AMapLaneInfo[] arg0, byte[] arg1, byte[] arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviViewLoaded() {
		// TODO Auto-generated method stub
		
	}

	@Override
	@Deprecated
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void notifyParallelRoad(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onArriveDestination(NaviStaticInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCalculateMultipleRoutesSuccess(int[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeStatistics(AimLessModeStat arg0) {
		// TODO Auto-generated method stub
		
	}

}
